package com.bawei.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.common.entity.VideoEntity
import com.bawei.home.databinding.ItemHomeVideoBinding
import com.bawei.image.ImageOptions
import com.bawei.image.ImageStrategy
import com.bawei.image.ImgLoader
import com.bumptech.glide.Glide
import kotlin.math.max

class ListVideoAdapter(private val list: MutableList<VideoEntity>): RecyclerView.Adapter<ListVideoAdapter.ItemViewHolder>(){

    //图片框架
    private var imgLoader: ImgLoader = ImgLoader.Builder.setImageStrategy(ImageStrategy.GLIDE).build()
    private var itemClickListener: OnItemClickListener? = null

    //定义预加载函数（方法）
    var onPreload: (()->Unit)? = null
    //预加载判断最后Item个数
    var preloadItemCount = 0
    //RecyclerView滚动状态
    private var scrollState = RecyclerView.SCROLL_STATE_IDLE
    //预加载状态
    private var isPreload = false

    //普通图片参数
    private var imgOption: ImageOptions = ImageOptions.Builder
        .setImageSize(intArrayOf(80, 80))
        .setCircleImage(false)
        .setErrorImage(com.bawei.common.R.drawable.ic_logo)
        .setPlaceImage(com.bawei.common.R.drawable.ic_logo)
        .skipMemoryCache(true)
        .build()

    //圆形图片参数
    private var imgCircleOption: ImageOptions = ImageOptions.Builder
        .setImageSize(intArrayOf(80, 80))
        .setCircleImage(true)
        .setErrorImage(com.bawei.common.R.drawable.ic_logo)
        .setPlaceImage(com.bawei.common.R.drawable.ic_logo)
        .skipMemoryCache(true)
        .build()

    //设置Item点击事件
     fun setOnItemClickListener(listener: OnItemClickListener){
        itemClickListener = listener
    }

    inner class ItemViewHolder(val dataBinding: ItemHomeVideoBinding): RecyclerView.ViewHolder(dataBinding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val dataBinding = ItemHomeVideoBinding.inflate(LayoutInflater.from(parent.context), parent,false)
        return ItemViewHolder(dataBinding)
    }

    override fun getItemCount(): Int = list.size

    /**
     * 不要在该方法中做耗时操作，大量计算，本地数据查询，创建大量对象
     */
    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val entity = list[position]
        //设置标题和描述
        holder.dataBinding.tvTitle.text = entity.title
        holder.dataBinding.tvDesc.text = entity.description
        //设置作者头像
        var avatarImageView = holder.dataBinding.ivAvatar
        imgLoader.loadUrlIntoImageView(holder.dataBinding.root.context, entity.avatar_url, avatarImageView, imgCircleOption)
        //视频图片
        var videoImageView = holder.dataBinding.ivVideoThumbnail
        imgLoader.loadUrlIntoImageView(holder.dataBinding.root.context, entity.videomainimag, videoImageView, imgOption)

        //设置监听事件(不要创建不必要的对象)
        holder.dataBinding.ivVideoPlay.setOnClickListener{
            itemClickListener?.onItemChildClick(it, position)
        }
        holder.dataBinding.ivCommend.setOnClickListener{
            itemClickListener?.onItemChildClick(it, position)
        }
        holder.dataBinding.ivMore.setOnClickListener{
            itemClickListener?.onItemChildClick(it, position)
        }

        //判断是否需要预加载数据
        checkPreload(position)
    }

    override fun onViewRecycled(holder: ItemViewHolder) {
        //从Glide中清除图片组件
        var avatarImageView = holder.dataBinding.ivAvatar
        Glide.with(holder.dataBinding.root.context).clear(avatarImageView)
        var videoImageView = holder.dataBinding.ivVideoThumbnail
        Glide.with(holder.dataBinding.root.context).clear(videoImageView)
    }

    /**
     * 当Adapter绑定到RecyclerView中的时候触发该方法
     */
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        //添加滚动事件，获取滚动状态
        recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState //记录滚动状态
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    /**
     * 检查是否满足预加载条件
     */
    private fun checkPreload(position: Int) {
       if (onPreload != null //只有设置预加载函数才触发预加载
           && position == max(list.size - 1 - preloadItemCount,0) //滚动到固定位置才触发预加载
           && scrollState != RecyclerView.SCROLL_STATE_IDLE //只有滚动状态才触发预加载
           && !isPreload //预加载过程中，不能进行过多加载
       ) {
           isPreload = true
           onPreload?.invoke()
       } else {
           //重置一下
           isPreload = false
       }
    }


    override fun getItemId(position: Int): Long {
        return list[position].id.toLong()
    }

    /**
     * 返回Item布局类型，如果使多布局，则返回不同类型，单一布局只返回一个值（0）
     */
    override fun getItemViewType(position: Int): Int {
        return 0
    }

    /**
     * 点击事件接口类
     */
     interface OnItemClickListener {
        fun onItemChildClick(v: View?, position: Int)
    }


}